import 'package:flutter/material.dart';

/// 如果没有固定的child直接使用NotifyBuilder更加方便,
/// 否则使用[AnimatedBuilder]即可。
class NotifyBuilder extends StatefulWidget {
  const NotifyBuilder(
    this.listenable, {
    Key? key,
    required this.builder,
  })  : assert(listenable != null),
        super(key: key);

  final Listenable listenable;
  final Widget Function() builder;

  @override
  State<StatefulWidget> createState() => _NotifyBuilderState();
}

class _NotifyBuilderState<T> extends State<NotifyBuilder> {
  @override
  void initState() {
    super.initState();
    widget.listenable?.addListener(_handleChange);
  }

  @override
  void didUpdateWidget(covariant NotifyBuilder oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.listenable != oldWidget.listenable) {
      oldWidget.listenable?.removeListener(_handleChange);
      widget.listenable?.addListener(_handleChange);
    }
  }

  @override
  void dispose() {
    widget.listenable?.removeListener(_handleChange);
    super.dispose();
  }

  //有时候_handleChange先执行(旧的元素被更新)再执行deactivate和dispose(顶层元素被销毁),
  //这是由于顶层不正确操作导致。
  void _handleChange() {
    setState(() {
      // The listenable's state is our build state, and it changed already.
    });
  }

  @override
  Widget build(BuildContext context) => widget.builder();
}
